from sqlmodel import Session,select
from . import models

# 创建用户
def create_user(session:Session, user:models.User):
    session.add(user)
    session.commit()
    session.refresh(user)
    return user

#根据id获取用户
def get_user(session:Session, user_id:int):
    return session.get(models.User, user_id)

# 分页面查询
def get_users(session:Session, page_index:int = 1, page_size:int = 10):
    return session.exec(select(models.User).offset((page_index-1)*page_size).limit(page_size)).all()

# 更新用户
def update_user(session:Session, user_id:int, user:models.User):
    db_user = session.get(models.User, user_id)
    if not db_user:
        return None
    user_data = user.model_dump(exclude_unset=True)
    for key, value in user_data.items():
        if key != "id":
            setattr(db_user, key, value)

    session.add(db_user)
    session.commit()
    session.refresh(db_user)
    return db_user

# 删除用户
def delete_user(session:Session, user_id:int):
    db_user = session.get(models.User, user_id)
    if not db_user:
        return False
    session.delete(db_user)
    session.commit()
    return True
